// 文件: Arrow.ts
import { _decorator, Component, Node, Vec3, v3, Quat, math, tween } from 'cc';
import { EnemyMovement } from './EnemyMovement'; // 导入敌人脚本，以便调用它的方法

const { ccclass, property } = _decorator;

@ccclass('Arrow')
export class Arrow extends Component {

    @property({ tooltip: "箭矢的飞行速度" })
    private speed: number = 1200; // 提高速度，让箭矢更有力

    private damage: number = 35; // 伤害为35，打3次差不多是100
    private direction: Vec3 = v3(); // 存储飞行方向，一旦确定就不再改变

    /**
     * 由 Archer 脚本在创建箭矢后调用
     * @param targetNode 目标敌人节点
     */
    public setTarget(targetNode: Node, damage: number) {
        if (!targetNode || !targetNode.isValid) {
            this.node.destroy();
            return;
        }

        this.damage = damage;

        const startPos = this.node.position.clone();
        const targetPos = targetNode.position.clone();

        const distance = Vec3.distance(startPos, targetPos);

        const flyTime = distance / this.speed;

        const direction = new Vec3();
        Vec3.subtract(direction, targetPos, startPos);
        const angle = Math.atan2(direction.y, direction.x) * 180 / Math.PI;
        this.node.angle = angle;

        tween(this.node)
            .to(flyTime, { position: targetPos }, {
                easing: 'linear' // 线性运动，保持恒定速度
            })
            .call(() => {
                // 到达目标后的回调
                this.hitTarget(targetNode, damage);
            })
            .start();
    }

    private hitTarget(targetNode: Node, damage: number) {
        if (targetNode && targetNode.isValid) {
            const enemyScript = targetNode.getComponent(EnemyMovement);
            if (enemyScript && !enemyScript.IsDead) {
                // 调用敌人身上的 takeDamage 方法
                enemyScript.takeDamage(this.damage);
            }
        }
        // 命中后，无论如何都销毁箭矢
        this.node.destroy();
    }
}
